package com.xkstream.client.ui;

import android.app.ActivityManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.xkstream.client.R;
import com.xkstream.client.api.API;
import com.xkstream.client.base.BaseActivity;
import com.xkstream.client.base.BaseData;
import com.xkstream.client.base.WatcherAdapter;
import com.xkstream.client.camera.CameraActivity;
import com.xkstream.client.common.CommonDialog;
import com.xkstream.client.http.FileUploadUtil;
import com.xkstream.client.presenter.kt.SendTalkContract;
import com.xkstream.client.presenter.kt.SendTalkPresenter;
import com.xkstream.client.rx.Rxbus;
import com.xkstream.client.utils.BitmapUtil;
import com.xkstream.client.utils.DeviceUtils;
import com.xkstream.client.utils.LeakUtil;
import com.xkstream.client.view.BottomPopupWindow;
import com.xkstream.client.view.FlowLayout;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * Created by xiaoyi on 2017-10-13.
 */

public class SendTalkActivity extends BaseActivity<SendTalkContract.Presenter>
        implements SendTalkContract.View {
    static final int TYPE_VIDEO = 0X1001;
    static final int TYPE_PHOTO = 0X1002;
    static final int TYPE_TEXT = 0X1003;
    @BindView(R.id.etContent)
    EditText etContent;
    @BindView(R.id.flContent)
    FlowLayout flContent;

    @BindString(R.string.exit_edit)
    String exitEdit;

    @BindView(R.id.textCount)
    TextView textCount;
    int type;
    String path;

    private MHandler mHandler;

    @BindView(R.id.tvSend)
    TextView tvSend;

    List<String> images = new ArrayList<>();
    List<String> videos = new ArrayList<>();

    private final static int CODE_PHOTO = 0X1001;

    private CompositeDisposable disposable;

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.activity_sendtalk);
        disposable = new CompositeDisposable();
        ButterKnife.bind(this);
        type = getIntent().getIntExtra("type", TYPE_PHOTO);
        path = getIntent().getStringExtra("path");
        mHandler = new MHandler(this);
        initView();
        presenter = new SendTalkPresenter(this);
    }

    @OnClick({R.id.tvCancel, R.id.tvSend})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvCancel:
                showExitDialog();
                break;
            case R.id.tvSend:
                publishBlog();
                break;
        }
    }

    private void publishBlog() {
        if (checkInput()) {
            Map<String, String> params = new HashMap<>();
            params.put("content", etContent.getText().toString());
            StringBuilder sb = new StringBuilder();
            for (String image : images) {
                sb.append(image).append(",");
            }
            String images;
            if (sb.toString().length() > 1) {
                images = sb.toString().substring(0, sb.toString().length() - 1);
                params.put("images", images);
            }
            if (!videos.isEmpty()) {
                params.put("videos", videos.get(0));
            }
            presenter.publishBlog(params);
        }
    }

    private boolean checkInput() {
        if (images.isEmpty() && videos.isEmpty()
                && TextUtils.isEmpty(etContent.getText().toString())) {
            showTopTips(R.string.say_somthing);
            return false;
        }
        return true;
    }

    private void showExitDialog() {
        CommonDialog dialog = new CommonDialog(this);
        dialog.setTitle(exitEdit);
        dialog.setListener(() -> {
            finish();
        });
        dialog.show();
    }

    private void initView() {
        if (type == TYPE_VIDEO) {
            addVideoView();
        } else if (type == TYPE_PHOTO) {
            addImageView(path);
        } else {
            addTextView();
        }

        etContent.addTextChangedListener(new WatcherAdapter(){
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
                textCount.setText(etContent.getText().toString().length()+"/200");
            }
        });

    }

    private void addVideoView() {
        ImageView iv = new ImageView(this);
        ViewGroup.MarginLayoutParams flParams = new ViewGroup.MarginLayoutParams(
                DeviceUtils.dp2px(this, 60), DeviceUtils.dp2px(this, 60)
        );

        RelativeLayout layout = new RelativeLayout(this);
        layout.addView(iv);

        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(path);

        Bitmap cover = media.getFrameAtTime();
        iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
        iv.setImageBitmap(cover);
        iv.setTag("video");
        upLoadFile(path, iv);
        ImageView play = new ImageView(this);
        play.setImageResource(R.drawable.icon_play);
        RelativeLayout.LayoutParams rlParams = new RelativeLayout.LayoutParams(flParams);
        rlParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        rlParams.width = DeviceUtils.dp2px(this, 30);
        rlParams.height = DeviceUtils.dp2px(this, 30);
        layout.addView(play, rlParams);

        flContent.addView(layout, flParams);
        flContent.setOnClickListener((v) -> {
            Intent intent = new Intent(this, VideoPlayActivity.class);
            intent.putExtra("path", path);
            jumpToActivity(intent);
        });
    }

    private void addImageView(String path) {

        ViewGroup.MarginLayoutParams rlParams =
                new ViewGroup.MarginLayoutParams(DeviceUtils.dp2px(this, 75),
                        DeviceUtils.dp2px(this, 75));
        int count = flContent.getChildCount();
        if (count == 0) {
            View child = View.inflate(this, R.layout.layout_photo_item, null);
            ImageView img = (ImageView) child.findViewById(R.id.ivImg);
            ImageView delete = (ImageView) child.findViewById(R.id.ivDelete);
            delete.setVisibility(View.GONE);
            img.setImageResource(R.drawable.img_add);
            flContent.addView(child, rlParams);
            child.setOnClickListener((v) -> {
                showPhotoSelectedDialog();
            });
            count++;
        }
        View child = View.inflate(this, R.layout.layout_photo_item, null);
        ImageView img = (ImageView) child.findViewById(R.id.ivImg);
        ImageView delete = (ImageView) child.findViewById(R.id.ivDelete);
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        img.setImageBitmap(bitmap);

        img.setTag("image");
        child.setTag(child.hashCode());
        delete.setOnClickListener((v) -> {
            int index = getChildIndex(flContent, child);
            images.remove(index);
            flContent.removeView(child);
            checkAddImageCount();
        });
        rlParams.rightMargin = DeviceUtils.dp2px(this, 10);
        rlParams.bottomMargin = DeviceUtils.dp2px(this, 10);
        flContent.addView(child, count - 1, rlParams);

        if (flContent.getChildCount() > 9) {
            flContent.removeViewAt(9);
        }
        upLoadFile(path, img);
    }

    private void checkAddImageCount() {
        ViewGroup.MarginLayoutParams rlParams =
                new ViewGroup.MarginLayoutParams(DeviceUtils.dp2px(this, 75),
                        DeviceUtils.dp2px(this, 75));
        if (flContent.getChildCount() == 8 && flContent.getChildAt(7).getTag() != null) {
            View child = View.inflate(this, R.layout.layout_photo_item, null);
            ImageView img = (ImageView) child.findViewById(R.id.ivImg);
            ImageView delete = (ImageView) child.findViewById(R.id.ivDelete);
            delete.setVisibility(View.GONE);
            img.setImageResource(R.drawable.img_add);
            flContent.addView(child, rlParams);
            child.setOnClickListener((v) -> {
                showPhotoSelectedDialog();
            });
        }
    }

    private void addTextView() {
        ViewGroup.MarginLayoutParams rlParams =
                new ViewGroup.MarginLayoutParams(DeviceUtils.dp2px(this, 75),
                        DeviceUtils.dp2px(this, 75));
        View child = View.inflate(this, R.layout.layout_photo_item, null);
        ImageView img = (ImageView) child.findViewById(R.id.ivImg);
        ImageView delete = (ImageView) child.findViewById(R.id.ivDelete);
        delete.setVisibility(View.GONE);
        img.setImageResource(R.drawable.img_add);
        flContent.addView(child, rlParams);
        child.setOnClickListener((v) -> {
            showPhotoSelectedDialog();
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String newPath = intent.getStringExtra("path");
        addImageView(newPath);
    }

    @Override
    public void showError(@NotNull String message) {
        showTopTips(message);
    }

    @Override
    public void showResult(@Nullable BaseData<Object> t) {
        if (t.getCode() == 1) {
            showTopTips(R.string.publish_success);
            tvSend.setEnabled(false);
            disposable .add( Observable.timer(2, TimeUnit.SECONDS)
                    .subscribe((l) -> {
                        finish();
                    }));
            Rxbus.getDefault().post("blog_refresh");
        } else {
            showTopTips(t.getMsg());

        }
    }

    @Override
    public void setPresenter(SendTalkContract.Presenter presenter) {
        this.presenter = presenter;
    }


    private void upLoadFile(String path, ImageView iv) {
        Map<String, String> textParams = new HashMap<>();
        textParams.put("bizImgPath", "show_h5");
        Map<String, String> params = new HashMap<>();
        params.put("iconFile", path);

        showLoading();
        new Thread(() -> {
            FileUploadUtil.uploadImageFile(API.FILEUPLOAD_HOST + API.UPLOAD_FILE,
                    textParams, params, mHandler, String.valueOf(iv.getTag()));
        }).start();

    }

    private static class MHandler extends Handler {
        WeakReference<SendTalkActivity> weakReference;

        public MHandler(SendTalkActivity activity) {
            this.weakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case FileUploadUtil.SUCCESS:
                    if (weakReference.get() != null) {
                        weakReference.get().hideLoading();
                        weakReference.get().handlerUploadMsg(msg);
                    }
                    break;
                case FileUploadUtil.FAILED:
                    if (weakReference.get() != null) {
                        weakReference.get().hideLoading();
                        weakReference.get().showTopTips(R.string.upload_failed);
                    }
                    break;

            }

        }
    }

    private void handlerUploadMsg(Message msg) {
        switch (msg.obj.toString()) {
            case "image":
                images.add(msg.getData().getString(FileUploadUtil.RESULT));
                break;
            case "video":
                videos.add(msg.getData().getString(FileUploadUtil.RESULT));
                break;


        }
    }

    @Override
    public void onBackPressed() {
        showExitDialog();
    }

    private void showPhotoSelectedDialog() {
        View view = View.inflate(this, R.layout.layout_choosephoto_dialog_zone, null);
        BottomPopupWindow popupWindow = new BottomPopupWindow(this, view);
        popupWindow.show(this);
        view.findViewById(R.id.tvCamera).setOnClickListener(
                (v) -> {
                    CameraActivity.lanuchForPhoto(this, true);
                    popupWindow.dismiss();

                }
        );
        view.findViewById(R.id.tvPhoto).setOnClickListener(
                (v) -> {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(intent, CODE_PHOTO);
                    popupWindow.dismiss();

                }
        );
        view.findViewById(R.id.tvCancel)
                .setOnClickListener((v) -> {
                    popupWindow.dismiss();
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_PHOTO && resultCode == RESULT_OK) {
            String path = getBitmapFromResult(data);
            addImageView(path);
        }
    }

    private String getBitmapFromResult(Intent data) {
        if (data != null) {

            String result = BitmapUtil.getPathByUri4kitkat(this,
                    data.getData() != null ? data.getData() :
                            Uri.parse(String.valueOf(data.getExtras().get("src_uri"))));
            return result;
        }
        return null;
    }

    private int getChildIndex(ViewGroup parent, View child) {
        int count = parent.getChildCount();
        for (int i = 0; i < count; i++) {
            if (parent.getChildAt(i).getTag().equals(child.getTag())) {
                return i;
            }
        }
        return -1;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disposable.dispose();
        LeakUtil.fixInputMethodManagerLeak(this);
    }
}
